<template>
  <div>
    <Spin :spinning="loading" tip="Loading...">
      <div ref="chart" class="chartWrap" :style="containerStyle" />
    </Spin>
  </div>
</template>

<script>
import echarts from 'echarts';
import config from '@/config';
// eharts  配置
const chartConf = config.charts;

export default {
  name: '',
  props: {
    option: {
      type: Object,
      default: () => ({})
    },
    params: {
      type: Object,
      default: () => ({})
    },
    dataSource: {
      type: [Array, Object],
      default: () => []
    },
    containerStyle: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    // echart 实例
    this.myChart = null;
    return {
      loading: false
    };
  },
  watch: {
    option() {
      this.initial();
    }
  },
  methods: {
    async initial() {
      this.loading = true;
      if (process.env.MOCK_DATA === 'true') {
        const { chart1 } = require('@/mock/chartData').default;
        this.draw(chart1);
      } else {
        this.draw(this.option);
      }
      this.loading = false;
    },
    draw(option) {
      let self = this;
      this.myChart = echarts.init(this.$refs.chart);
      if (option && this.myChart) {
        this.myChart.clear();
        this.myChart.setOption(option, true);
      }
    },
    resize(){
      this.myChart = echarts.init(this.$refs.chart);
      this.myChart.resize();
    }
  },
  mounted() {
    this.initial();
    // 监听resize方法
    window.addEventListener("resize", this.resize, false);
  },
  beforeDestroy() {
    // 移除监听
    window.removeEventListener("resize", this.resize, false)
    if (this.myChart) {
      this.myChart.dispose();
    }
    this.myChart = null;
  }
};
</script>

<style lang="less" scoped>
.chartWrap {
  width: 100%;
  // min-height: 400px;
}
</style>
